package com.willian.andrappfw.network.interceptor;

import java.io.EOFException;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;

import android.text.TextUtils;

import com.willian.andrappfw.AppBuildConfig;
import com.willian.andrappfw.utils.FormatUtils;
import com.willian.andrappfw.utils.LogUtils;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Interceptor.Chain;
import okio.Buffer;
import okio.BufferedSource;
import org.jetbrains.annotations.NotNull;

public class LogInterceptor implements Interceptor {
    private final String TAG = "_Log";
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private static int iRequestNo = 0;
    private final String RETROFIT_TAG = "Retrofit";

    public LogInterceptor() { }

    @NotNull
    public Response intercept(@NotNull Chain chain) throws IOException {

        if (!AppBuildConfig.DEBUG) {
            return chain.proceed(chain.request());
        } else {
            int requestNo = ++iRequestNo;
            Request request = chain.request();
            HttpUrl httpUrl = request.url();
            String url = httpUrl.toString();
            String paramsStr = null;
            RequestBody requestBody = request.body();
            String requestBodyStr = null;
            if (requestBody != null) {
                requestBodyStr = getRequestBodyContent(requestBody);

                try {
                    requestBodyStr = URLDecoder.decode(requestBodyStr, "UTF-8");
                } catch (Exception var19) {
                }
            } else {
                HashMap<String, String> params = new HashMap();
                Iterator var10 = httpUrl.queryParameterNames().iterator();

                while(var10.hasNext()) {
                    String name = (String)var10.next();
                    params.put(name, httpUrl.queryParameter(name));
                }

                paramsStr = FormatUtils.mapToString(params);
            }

            this.printLog(requestNo, (String)null, "<-----------Begin");
            String requestTime = FormatUtils.getTimeString();
            long requestTimeLong = System.currentTimeMillis();
            this.printLog(requestNo, (String)null, "requestTime:" + requestTime);
            this.printLog(requestNo, (String)null, "url:" + url);
            this.printLog(requestNo, (String)null, "headers:" + request.headers().toString().replaceAll("\\n", "|"));
            if (!TextUtils.isEmpty(paramsStr)) {
                this.printLog(requestNo, (String)null, "params:" + paramsStr);
            }

            if (!TextUtils.isEmpty(requestBodyStr)) {
                this.printLog(requestNo, (String)null, "requestBody:" + requestBodyStr);
            }

            request = request.newBuilder().tag(requestNo).build();

            Response response;
            try {
                response = chain.proceed(request);
            } catch (Exception var20) {
                this.printLog(requestNo, (String)null, "errorMessage:" + var20);
                StackTraceElement[] var14 = var20.getStackTrace();
                int var15 = var14.length;

                for(int var16 = 0; var16 < var15; ++var16) {
                    StackTraceElement element = var14[var16];
                    this.printLog(requestNo, (String)null, "errorMessage:at " + element);
                }

                this.printLog(requestNo, (String)null, "<-----------End");
                throw var20;
            }

            String responseTime = FormatUtils.getTimeString();
            this.printLog(requestNo, (String)null, "responseTime:" + responseTime);
            long costTime = System.currentTimeMillis() - requestTimeLong;
            this.printLog(requestNo, (String)null, "costTime:" + costTime + "ms");
            if (response.body() != null && this.isTextResponse(response)) {
                long contentLength = response.body().contentLength();
                String responseContent = this.readResponseStr(response);
                if (contentLength != -1L) {
                    this.printLog(requestNo, (String)null, "contentLength:" + contentLength);
                } else {
                    contentLength = (long)responseContent.getBytes().length;
                    this.printLog(requestNo, (String)null, "contentLength:" + contentLength + " byte body");
                }

                this.printContent("Retrofit_Log[#" + requestNo + "]", "responseContent:\n" + FormatUtils.getReadableString(responseContent));
                this.printLog(requestNo, (String)null, "<-----------End");
            }

            return response;
        }
    }

    private boolean isTextResponse(Response response) {
        if (response != null && response.body() != null && response.body().contentType() != null) {
            String contentType = response.body().contentType().toString();
            String type = response.body().contentType().type();
            return "text".equals(type) || contentType.contains("json") || contentType.contains("xml");
        } else {
            return false;
        }
    }

    private void printLog(int requestNo, String apiName, String log) {
        LogUtils.d("Retrofit_Log[#" + requestNo + "]" + (apiName != null ? "[" + apiName + "]" : ""), log);
    }

    private void printContent(String tag, String msg) {
        if (true) {
            int strLength = msg.length();
            int start = 0;
            int LOG_MAXLENGTH = 2000;
            int end = LOG_MAXLENGTH;

            for(int i = 0; i < 100; ++i) {
                if (strLength <= end) {
                    LogUtils.d(tag, msg.substring(start, strLength));
                    break;
                }

                LogUtils.d(tag + "[" + i + "]", msg.substring(start, end));
                start = end;
                end += LOG_MAXLENGTH;
            }

        }
    }

    private String readResponseStr(Response response) {
        ResponseBody body = response.body();
        BufferedSource source = body.source();

        try {
            source.request(9223372036854775807L);
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }

        MediaType contentType = body.contentType();
        Charset charset = Charset.forName("UTF-8");
        if (contentType != null) {
            charset = contentType.charset(charset);
        }

        String s = null;
        Buffer buffer = source.buffer();
        if (this.isPlaintext(buffer) && charset != null) {
            s = buffer.clone().readString(charset);
        }

        return s;
    }

    private boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64L ? buffer.size() : 64L;
            buffer.copyTo(prefix, 0L, byteCount);

            for(int i = 0; i < 16 && !prefix.exhausted(); ++i) {
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }

            return true;
        } catch (EOFException var7) {
            return false;
        }
    }

    private static String getRequestBodyContent(RequestBody requestBody) {
        String body = "";
        if (requestBody != null) {
            Buffer buffer = new Buffer();

            try {
                requestBody.writeTo(buffer);
            } catch (IOException var5) {
            }

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (charset != null) {
                body = buffer.readString(charset);
            }
        }

        return body;
    }
}
